package com.lib76.jsp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * HTTPSevlet工具
 * @author 张浩
 * @version 0.0.1
 */
public class HttpServletUtils {
	
	public static ThreadLocal<HttpServletRequest> Request = new ThreadLocal<HttpServletRequest>();

	public static ThreadLocal<HttpServletResponse> Response = new ThreadLocal<HttpServletResponse>();
	
	/**
	 * 跳转页面，必须创建一个404页面
	 * @param path
	 */
	public static String sendRedirect(String path){
		try{
			HttpServletRequest req = Request.get();
			if(req != null){
				HttpServletResponse resp = Response.get();
				resp.sendRedirect(req.getContextPath() + path);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return "404";
	}
	
	/**
	 * 跳转页面
	 * @param path
	 */
	public static String sendRedirect(String path,String template){
		try{
			HttpServletRequest req = Request.get();
			if(req != null){
				HttpServletResponse resp = Response.get();
				resp.sendRedirect(req.getContextPath() + path);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return template;
	}
	
	public static String getRealPath(String path){
		try{
			HttpServletRequest req = Request.get();
			if(req != null){
				return req.getSession(true).getServletContext().getRealPath(path);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
}
